<?php
/**
 * 业务数据导入
 *
 * User: kaikaic
 * Date: 2018/11/28
 * Time: 13:50
 */

namespace app\exam\controller;

use app\exam\service\EnterpriseService;
use app\exam\service\GroupApplyService;
use app\exam\service\GroupService;
use app\exam\service\GroupSetService;
use app\exam\service\MecItemService;
use app\exam\service\MecService;
use app\exam\service\MecSetService;
use app\exam\service\MessageService;
use controller\BasicAdmin;
use service\ConfigService;
use service\ExcelService;
use service\FileService;
use think\Db;

/**
 * 一次性使用，后期删除
 */

class Import extends BasicAdmin {

    protected $table = "";

    /**
     * 导入体检机构
     */
    public function index() {
        $excelFile = "/data.xls";
        $result = $this->readExcelFile($excelFile);

        echo "导入数据:" . $result;exit;
    }

    /**
     * 导入体检套餐
     */
    public function set() {
        $excelFile = "/data.xls";
        $result = $this->importSet($excelFile);

        echo "导入数据:" . $result;exit;
    }

    /**
     * 体检项目
     */
    public function item() {
        $excelFile = "/data.xls";
        $result = $this->importItem($excelFile);

        echo "导入数据:" . $result;exit;
    }

    /**
     * 体检项目
     */
    private function importItem($excelFile) {
        $excelFile = env('root_path') . $excelFile;
        $excelData = ExcelService::importExcel($excelFile, 2);
        if (!$excelData) {
            return 0;
        }

        $size = count($excelData);
        $importCount = 0;
        $uniqueCode = "";
        for ($i=0; $i<$size; $i++) {
            $tmp = $excelData[$i];
            $code = $tmp[0];

            if ($code) {
                $uniqueCode = $code;
            }

            $params = array();
            $params['unique_code'] = $uniqueCode;
            $params['name'] = $tmp[2];
            $params['intro'] = $tmp[3];
            $params['purpose'] = $tmp[4];

            $params['taboo'] = "";
            $params['sort'] = 0;
            $params['status'] = 1;
            $params['create_time'] = time();

            // 数据记录
            $rs = $this->doImportItem($params);
            if ($rs) {
                $importCount++;
            }
        }

        return $importCount;
    }

    /**
     * 体检套餐
     */
    private function importSet($excelFile) {
        $excelFile = env('root_path') . $excelFile;
        $excelData = ExcelService::importExcel($excelFile, 1);
        if (!$excelData) {
            return 0;
        }

        $importCount = 0;
        for ($i=0; $i<count($excelData); $i++) {
            $tmp = $excelData[$i];

            $params = array();
            $params['unique_code_mec'] = $tmp[1];
            $params['unique_code'] = $tmp[2];

            $params['name'] = $tmp[3];
            $params['price'] = $tmp[4];
            $params['applicable_ser'] = $tmp[5];
            $params['comment'] = $tmp[6];

            $params['old_price'] = $params['price'];
            $params['intro'] = "";
            $params['main_info'] = "";

            $params['set_type'] = 1;
            $params['sort'] = 0;
            $params['status'] = 1;
            $params['create_time'] = time();

            // 数据记录
            $rs = $this->doImportSet($params);
            if ($rs) {
                $importCount++;
            }
        }

        return $importCount;
    }

    /**
     * 体检中心
     */
    private function readExcelFile($excelFile) {
        $excelFile = env('root_path') . $excelFile;
        $excelData = ExcelService::importExcel($excelFile);
        if (!$excelData) {
            return 0;
        }

        $importCount = 0;
        for ($i=0; $i<count($excelData); $i++) {
            $tmp = $excelData[$i];
            if (count($tmp) != 7) {
                continue;
            }

            $params = array();
            $params['unique_code'] = $tmp[0];
            $params['name'] = $tmp[1];
            $params['intro'] = $tmp[2];
            $params['phone'] = $tmp[3];
            $params['address'] = $tmp[5];
            $params['logo'] = $tmp[4];

            $params['worktime'] = "08:00 ~ 18:00";
            $params['tags'] = "";
            $params['category_id'] = 12;        // 默认体检机构
            $params['province_id'] = 18;        // 默认湖南
            $params['city_id'] = 275;           // 默认长沙
            $params['district_id'] = 2914;      // 默认天心区

            $params['sort'] = 0;
            $params['status'] = 1;
            $params['create_time'] = time();

            // 数据记录
            $rs = $this->doImport($params);
            if ($rs) {
                $importCount++;
            }
        }

        return $importCount;
    }

    private function doImportItem($data) {
        if (!$data['unique_code']) {
            return false;
        }

        // 如果套餐code不存在
        $record = MecSetService::getInstance()->single(array('unique_code'=>$data['unique_code']));
        if (!$record) {
            return false;
        }

        /**
         * 体检机构-默认体检项目分类
         */
        $mecID = $record['mec_id'];
        $itemSetID = 0;
        $itemSet = MecItemService::getInstance()->single(array('mec_id'=>$mecID, 'is_default'=>1));
        if (!$itemSet) {
            $itemSetID = MecItemService::getInstance()->initDefaultClass($mecID);
            if (!$itemSetID) {
                return false;
            }
        }else {
            $itemSetID = $itemSet['id'];
        }

        // 去重
        $item = MecItemService::getInstance()->single(array('mec_id'=>$mecID, 'name'=>$data['name']), 1);
        if ($item) {
            $this->updateSetItem($record, $item['id']);

            return true;
        }

        $data['mec_id'] = $mecID;
        $data['item_set_id'] = $itemSetID;
        unset($data['unique_code']);

        $recordID = MecItemService::getInstance()->insert($data, 1);
        if (!$recordID) {
            return false;
        }

        $this->updateSetItem($record, $item['id']);

        return true;
    }

    private function doImportSet($data) {
        if (!$data['unique_code']) {
            return false;
        }

        // 唯一编号已存在
        $record = MecSetService::getInstance()->single(array('unique_code'=>$data['unique_code']));
        if ($record) {
            return false;
        }

        // 获得体检中心ID
        $mec = MecService::getInstance()->single(array('unique_code'=>$data['unique_code_mec']));
        if (!$mec) {
            return false;
        }

        unset($data['unique_code_mec']);
        $data['mec_id'] = $mec['id'];
        $data['item_ids'] = serialize(array());

        $recordID = MecSetService::getInstance()->insert($data);
        if (!$recordID) {
            return false;
        }

        return true;
    }

    private function doImport($data) {
        if (!$data['unique_code']) {
            return false;
        }

        $record = MecService::getInstance()->single(array('unique_code'=>$data['unique_code']));
        if ($record) {
            return false;
        }

        $data['logo'] = $this->downloadLogo($data['logo']);

        $recordID = MecService::getInstance()->insert($data);
        if (!$recordID) {
            return false;
        }

        return true;
    }

    /**
     * 更新套餐-体检项目
     */
    private function updateSetItem($set, $itemID) {
        $itemIDs = unserialize($set['item_ids']);
        if (in_array($itemID, $itemIDs)) {
            return true;
        }
        $itemIDs[] = $itemID;

        $update = array();
        $update['item_ids'] = serialize($itemIDs);

        MecSetService::getInstance()->update($update, $set['id']);
    }

    private function downloadLogo($logoFile) {
        $logoFile = trim($logoFile);
        if (!$logoFile) {
            return "";
        }

        $savePath = "/static/upload/logo";

        $ext = strtolower(pathinfo($logoFile, 4));
        $localFile = $savePath . "/" . md5($logoFile) . "." . $ext;

        $content = file_get_contents($logoFile);
        file_put_contents(env('root_path') . $localFile, $content);

        return $localFile;
    }
}

